package com.module.prms.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import base.dao.GenericHibernateDao;
import base.util.Page;
import base.util.Tools;

import com.module.prms.vo.PrmsRole;



public class RoleDao extends GenericHibernateDao<PrmsRole, String> {

	private RoleDao() {
	}

	private static RoleDao dao;

	public synchronized static RoleDao getInstance() {
		if (dao == null)
			dao = new RoleDao();
		return dao;
	}

	/**
	 * 角色列表 huhui 2011-07-30
	 * 
	 * @param bean
	 *            用户实体bean
	 * @param start
	 *            数据起始值
	 * @param limit
	 *            查询数量
	 * @return Page
	 */

	public Page getList(Session session, PrmsRole bean, Integer start,
			Integer limit) {
		Page page = new Page();
		page.setStart(start);
		page.setLimit(limit);
		StringBuffer sb = new StringBuffer();
		StringBuffer condition = new StringBuffer();
		List<Object> params = new ArrayList<Object>();
		if (Tools.isValid(bean.getCroleName())) {
			condition.append(" and obj.croleName like ?");
			params.add("%" + bean.getCroleName() + "%");
		}


		if (bean.getOrgPid().equals("0")) {
			sb.append("from PrmsRole as obj where 1=1 ");
		} else {
			sb.append("from PrmsRole as obj where  obj.orgid in("
					+ bean.getOrgid() + ")");
		}
		sb.append(condition);
		sb.append(" ORDER BY orgid ASC,droleOptTime DESC ");
		Query query = session.createQuery(sb.toString());
		int i = 0;
		for (Object obj : params) {
			query.setParameter(i, obj);
			i++;
		}
		query.setFirstResult(start).setMaxResults(limit);

		Query totalQuery = session.createQuery("select count(*) " + sb);
		int j = 0;
		for (Object obj : params) {
			totalQuery.setParameter(j, obj);
			j++;
		}
		page.setTotal((long) ((Long) totalQuery.uniqueResult()).intValue());
		page.setRows(query.list());
		return page;
	}

	/**
	 * 组织下角色列表 huhui 2011-07-30
	 * 
	 * @param bean
	 *            用户实体bean
	 * @param start
	 *            数据起始值
	 * @param limit
	 *            查询数量
	 * @return Page
	 */
	public List getorgrole(Session session, String orgid) {
		StringBuffer sb = new StringBuffer();
		sb.append("from PrmsRole as obj where obj.orgid=?");
		Query query = session.createQuery(sb.toString());
		query.setString(0, orgid);
		List list = query.list();
		return list;
	}
	
	public long getRoleByOrg(Session session, String orgid){
		String hql = "select count(*) from PrmsRole where orgid in ("+orgid+")";
		Query countQuery = session.createQuery(hql);
    	return (long) ((Long) countQuery.uniqueResult()).intValue();
	}

}
